package org.wei.tbk;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class TBKShopServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		doPost(req, resp);
}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String entity = req.getParameter("entity");
		// option表示针对管理类别的操作，如：增，删，查，改等
		String option = req.getParameter("option");
		
		//引导页面，填写
		if(entity==null || entity.trim().equals("")) {
			resp.sendRedirect("tbk/step1-Uploadcvs.jsp");
			return;			
		}

		//1.提交店铺qq号，提交cvs文件
		if(entity.equals("step1")){
			String shopId = req.getParameter("shopId");
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iterator = null;
			try {
				iterator = upload.getItemIterator(req);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			try {
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream stream = item.openStream();
					if (item.isFormField()) {
						// Handle form field
					} else {
						// Handle the uploaded file
						if(! item.getFieldName().endsWith("cvs")) {
							//去另一个地方。。。
						}
						File ff = new File("c:/0001.cvs");

						//查询<自定义分类id：自定义分类中文名> 集合对
						//HashMap<String,String> map = APIInvoke.invoke(shopId);
						HashMap<String,String> map = new HashMap<String,String>();
						//商品导出cvs文件转换
						String out = CVSHandle.covert(stream, map);
						
						
						
						//写到db，存起来
//						Blob cvsOrig = new Blob(IOUtils.toByteArray(stream));
//						Blob cvsDest = new Blob(out.getBytes());
//						ShopProp prop = new ShopProp(shopId, cvsOrig, cvsDest);
//						TBKDao.getInstance().insert(prop);
						
						resp.setCharacterEncoding("UTF-16");
						resp.setHeader("Content-disposition","attachment;filename=success.csv");
						resp.setContentType("text/csv");
						resp.getWriter().print(out);
						resp.getWriter().flush();
						resp.getOutputStream().close();
						return;
					}

				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
		
		
		//2.输出转换关系
		if(entity.equals("step2")){
			String shopId = req.getParameter("shopId");
			APIInvoke.invoke(shopId);
		}
		//3.导出cvs
	}

}
